package com.ruben.leetCode;/**
 * @ClassName: RelativeSortArraySolution
 * @Date: 2020/11/14 0014 12:10
 * @Description:
 */

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: RelativeSortArraySolution
 * @Description: 我还没有写描述
 * @Date: 2020/11/14 0014 12:10
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class RelativeSortArraySolution {

    public static void main(String[] args) {
        RelativeSortArraySolution solution = new RelativeSortArraySolution();
//        Arrays.stream(solution.relativeSortArray(new int[]{2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19}, new int[]{2, 1, 4, 3, 9, 6})).forEach(System.out::println);
        Arrays.stream(solution.relativeSortArray(new int[]{943, 790, 427, 722, 860, 550, 225, 846, 715, 320}, new int[]{943, 715, 427, 790, 860, 722, 225, 320, 846, 550})).forEach(System.out::println);
    }


    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        List<Integer> result = new ArrayList<>(arr1.length);
        Map<Boolean, List<Integer>> filtered = Arrays.stream(arr1).boxed().collect(Collectors.groupingBy(i -> Arrays.stream(arr2).boxed().anyMatch(i::equals)));
        Map<Integer, List<Integer>> listMap = filtered.getOrDefault(true, new ArrayList<>()).stream().collect(Collectors.groupingBy(Integer::intValue));
        Arrays.stream(arr2).forEach(i -> result.addAll(listMap.get(i)));
        result.addAll(filtered.getOrDefault(false, new ArrayList<>()).stream().sorted().collect(Collectors.toList()));
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}
